<template>
	<view class="attendance-container">
		<!-- 项目选择 -->
		<view class="section project-section" v-if="projectList.length > 0">
			<text class="section-title">选择项目</text>
			<view class="project-selector">
				<picker @change="onProjectChange" :value="currentProjectIndex" :range="projectList"
					range-key="project_name">
					<view class="picker-content">
						<text class="picker-text">{{ currentProject.project_name || '请选择项目' }}</text>
						<text class="picker-arrow">▼</text>
					</view>
				</picker>
			</view>
		</view>

		<!-- 地图区域 -->
		<view class="map-container">
			<map id="attendanceMap" :latitude="locationCoords.latitude" :longitude="locationCoords.longitude"
				:markers="mapMarkers" :circles="mapCircles" scale="16" class="attendance-map">
			</map>

			<!-- 打卡范围提示 -->
			<view class="map-overlay" :class="{ 'in-range': isInRange }">
				<text class="range-text">{{ isInRange ? '在打卡范围内' : '不在打卡范围内' }}</text>
				<text class="range-help">有疑问? 查看帮助 ></text>
			</view>
		</view>

		<view class="location-info">
			<text class="location-title">当前位置: </text>
			<text class="location-text">{{ currentLocation }}</text>
		</view>

		<!-- 打卡按钮 -->
		<view class="punch-container">
			<view class="punch-circle" @tap="punchClock" :class="{ 'disabled': isProcessing || !isInRange }">
				<view class="punch-content">
					<text class="punch-type">{{ getPunchButtonText() }}</text>
					<text class="punch-time">{{ currentHourMinute }}</text>
					<text class="punch-note">{{ getPunchNote() }}</text>
				</view>
			</view>
		</view>

		<!-- 打卡时间提示 -->
		<view class="work-time-info">
			<text class="work-time-text">上班09:00 — 下班18:00</text>
		</view>

		<!-- 考勤记录 -->
		<view class="attendance-records" v-if="false">
			<text class="records-title">本周考勤记录</text>
			<view class="records-list">
				<view v-if="attendanceRecords.length === 0 && !recordsLoading" class="empty-data">
					<text class="empty-text">暂无考勤记录</text>
				</view>
				<view class="record-item" v-for="(record, index) in attendanceRecords" :key="index">
					<view class="record-date">
						<text class="date">{{ record.date }}</text>
						<text class="weekday">{{ record.weekday }}</text>
					</view>
					<view class="record-times">
						<text class="time-in">{{ record.checkIn || '--:--' }}</text>
						<text class="time-out">{{ record.checkOut || '--:--' }}</text>
					</view>
					<text class="record-status" :class="record.status">{{ getStatusText(record.status) }}</text>
				</view>
				<view v-if="recordsLoading" class="loading-data">
					<text class="loading-text">加载中...</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { attendanceApi, projectApi } from '@/common/api'
import { isLoggedIn, getCurrentUser, getProjects } from '@/common/auth'
import config from '@/common/config'

// 定义项目类型接口
interface Project {
	project_id: string;
	project_name: string;
	latitude: number;
	longitude: number;
	address: string;
}

// 状态变量
const currentTime = ref('')
const currentDate = ref('')
const currentLocation = ref('正在获取位置...')
const locationCoords = ref({ latitude: 39.908823, longitude: 116.397470 }) // 默认北京坐标
const checkedIn = ref(false)
const checkInTime = ref('')
const checkOutTime = ref('')
const isProcessing = ref(false)
const recordsLoading = ref(false)
const attendanceRecords = ref([])
const isInRange = ref(false)

// 项目相关变量
const projectList = ref<Project[]>([])
const currentProjectIndex = ref(0)
const currentProject = ref<Project>({
	project_id: '',
	project_name: '请选择项目',
	latitude: 39.908823,
	longitude: 116.397470,
	address: '默认位置'
})

// 打卡地点配置
const checkInLocation = ref({
	latitude: 39.908823,
	longitude: 116.397470,
	name: '打卡地点',
	radius: 200 // 打卡范围半径（米）
})

// 地图标记点
const mapMarkers = ref([
	{
		id: 1,
		latitude: checkInLocation.value.latitude,
		longitude: checkInLocation.value.longitude,
		iconPath: '/static/location-marker.png', // 需要添加这个图标
		width: 30,
		height: 30,
		callout: {
			content: '打卡地点',
			color: '#333333',
			fontSize: 12,
			borderRadius: 4,
			bgColor: '#ffffff',
			padding: 5,
			display: 'ALWAYS'
		}
	},
	{
		id: 2,
		latitude: locationCoords.value.latitude,
		longitude: locationCoords.value.longitude,
		iconPath: '/static/user-location.png', // 需要添加这个图标
		width: 30,
		height: 30
	}
])

// 地图圆形区域（打卡范围）
const mapCircles = ref([
	{
		latitude: checkInLocation.value.latitude,
		longitude: checkInLocation.value.longitude,
		color: '#2B5BA133', // 半透明蓝色
		fillColor: '#4A90E233', // 更透明的填充色
		radius: checkInLocation.value.radius,
		strokeWidth: 1
	}
])

// 当前小时和分钟，用于显示在打卡按钮上
const currentHourMinute = computed(() => {
	const now = new Date()
	const hours = String(now.getHours()).padStart(2, '0')
	const minutes = String(now.getMinutes()).padStart(2, '0')
	return `${hours} ${minutes}`
})

// 加载项目列表
const loadProjects = async () => {
	try {
		const projects = getProjects()
		if (projects && projects.length > 0) {
			// 通过API获取项目位置信息
			const res = await projectApi.getProjectLocation(projects.map((project: { project_id: string }) => project.project_id))
			if (res.success && res.data) {
				projectList.value = res.data.map((project: { project_id: string; project_name: string; latitude: number; longitude: number; address: string }) => ({
					project_id: project.project_id,
					project_name: project.project_name,
					latitude: project.latitude,
					longitude: project.longitude,
					address: project.address,
				}))

			}

			// 设置默认选中的项目
			if (projectList.value.length > 0) {
				currentProject.value = projectList.value[0]
				updateCheckInLocation()
			}
		}
	} catch (error) {
		console.error('获取项目列表失败:', error)
	}
}

// 项目选择变更
const onProjectChange = (e: { detail: { value: number } }) => {
	const index = e.detail.value
	currentProjectIndex.value = index
	currentProject.value = projectList.value[index]

	// 更新打卡位置
	updateCheckInLocation()
}

// 更新打卡位置
const updateCheckInLocation = () => {
	// 由于我们已经定义了Project接口并使用ref<Project>，TypeScript现在知道location属性一定存在
	checkInLocation.value = {
		latitude: currentProject.value.latitude,
		longitude: currentProject.value.longitude,
		name: currentProject.value.project_name,
		radius: 200 // 打卡范围半径（米）
	}

	// 更新地图标记和圆形区域
	if (mapMarkers.value[0] && mapMarkers.value[0].callout) {
		mapMarkers.value[0].latitude = checkInLocation.value.latitude
		mapMarkers.value[0].longitude = checkInLocation.value.longitude
		mapMarkers.value[0].callout.content = currentProject.value.project_name
	}

	mapCircles.value[0].latitude = checkInLocation.value.latitude
	mapCircles.value[0].longitude = checkInLocation.value.longitude

	// 重新检查是否在打卡范围内
	checkInRange(locationCoords.value.latitude, locationCoords.value.longitude)
}

// 更新当前时间
const updateTime = () => {
	const now = new Date()
	const hours = String(now.getHours()).padStart(2, '0')
	const minutes = String(now.getMinutes()).padStart(2, '0')
	const seconds = String(now.getSeconds()).padStart(2, '0')
	currentTime.value = `${hours}:${minutes}:${seconds}`

	const year = now.getFullYear()
	const month = String(now.getMonth() + 1).padStart(2, '0')
	const day = String(now.getDate()).padStart(2, '0')
	const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
	currentDate.value = `${year}年${month}月${day}日 ${weekdays[now.getDay()]}`
}

// 获取位置信息
const getLocation = () => {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02', // 使用国测局坐标系
			success: (res: UniApp.GetLocationSuccess) => {
				locationCoords.value = {
					latitude: res.latitude,
					longitude: res.longitude
				}

				// 更新用户位置标记
				mapMarkers.value[1].latitude = res.latitude
				mapMarkers.value[1].longitude = res.longitude

				// 检查是否在打卡范围内
				checkInRange(res.latitude, res.longitude)

				// 使用逆地理编码获取地址
				uni.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${config.mapKey}`,
					success: (geoRes: any) => {
						if (geoRes.statusCode === 200 && geoRes.data.status === 0) {
							currentLocation.value = geoRes.data.result.address
							console.log("currentLocation.value", currentLocation.value)
							resolve(currentLocation.value)
						} else {
							// 如果逆地理编码失败，显示坐标
							currentLocation.value = `位置: ${res.latitude.toFixed(6)}, ${res.longitude.toFixed(6)}`
							resolve(currentLocation.value)
						}
					},
					fail: () => {
						currentLocation.value = `位置: ${res.latitude.toFixed(6)}, ${res.longitude.toFixed(6)}`
						resolve(currentLocation.value)
					}
				})
			},
			fail: (err: any) => {
				console.error('获取位置失败:', err)
				currentLocation.value = '位置获取失败，请检查定位权限'
			}
		})
	})
}

// 检查是否在打卡范围内
const checkInRange = (latitude: number, longitude: number) => {
	// 计算两点之间的距离（使用简化的方法，实际项目可能需要更精确的计算）
	const distance = calculateDistance(
		latitude,
		longitude,
		checkInLocation.value.latitude,
		checkInLocation.value.longitude
	)

	isInRange.value = distance <= checkInLocation.value.radius
	console.log('距离打卡点:', distance.toFixed(0), '米, 是否在范围内:', isInRange.value)
}

// 计算两个坐标点之间的距离（单位：米）
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
	const R = 6371000 // 地球半径，单位米
	const dLat = (lat2 - lat1) * Math.PI / 180
	const dLon = (lon2 - lon1) * Math.PI / 180
	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		Math.sin(dLon / 2) * Math.sin(dLon / 2)
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
	return R * c
}

// 刷新位置
const refreshLocation = async () => {
	currentLocation.value = '正在获取位置...'
	await getLocation()
}

// 加载今日考勤状态
const loadTodayAttendance = async () => {
	if (!isLoggedIn()) return

	try {
		const res = await attendanceApi.getTodayStatus()
		if (res.success && res.data) {	
			const { check_in, check_out } = res.data
			checkedIn.value = !!check_in		
			if (check_in) {
				checkInTime.value = formatTime(new Date(check_in))
			}

			if (check_out) {
				checkOutTime.value = formatTime(new Date(check_out))
			}
		}
	} catch (error) {
		console.error('获取今日考勤状态失败:', error)
	}
}

// 格式化时间为 HH:MM 格式
const formatTime = (date: Date): string => {
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	return `${hours}:${minutes}`
}

// 获取打卡按钮文本
const getPunchButtonText = () => {	
	if (isProcessing.value) return '处理中...'
	if (!checkedIn.value) return '上班打卡'
	if (checkedIn.value) return '下班打卡'
	return '今日已完成'
}

// 获取打卡提示文本
const getPunchNote = () => {
	if (!checkedIn.value) return '请09:00前打卡'
	if (checkedIn.value) return '请18:00后打卡'
	return '打卡已完成'
}

// 打卡操作
const punchClock = async () => {
	if (isProcessing.value) return
	if (!isLoggedIn()) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}

	if (!isInRange.value) {
		uni.showToast({
			title: '不在打卡范围内',
			icon: 'none'
		})
		return
	}

	if (!currentProject.value.project_id) {
		uni.showToast({
			title: '请先选择项目',
			icon: 'none'
		})
		return
	}

	isProcessing.value = true

	try {
		// 再次获取位置
		await refreshLocation()

		const punchType = !checkedIn.value ? 'check_in' : 'check_out'

		const punchData = {
			type: punchType,
			location: currentLocation.value,
			coordinates: {
				latitude: locationCoords.value.latitude,
				longitude: locationCoords.value.longitude
			},
			project_id: currentProject.value.project_id,
			timestamp: new Date().toISOString()
		}

		const res = await attendanceApi.clockIn(punchData)
		
		if (res.success) {
			const now = new Date()
			const timeStr = formatTime(now)

			if (punchType === 'check_in') {
				checkedIn.value = true
				checkInTime.value = timeStr
			uni.showToast({
					title: '上班打卡成功',
				icon: 'success'
			})
			} else {
				checkedIn.value = false
				checkOutTime.value = timeStr
				uni.showToast({
					title: '下班打卡成功',
					icon: 'success'
				})
			}

			// 刷新考勤记录
			loadAttendanceRecords()
		} else {
			uni.showToast({
				title: res.message || '打卡失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('打卡失败:', error)
		uni.showToast({
			title: '打卡失败，请重试',
			icon: 'none'
		})
	} finally {
		isProcessing.value = false
	}
}

// 获取考勤状态文本
const getStatusText = (status: string): string => {
	const statusMap: Record<string, string> = {
		'normal': '正常',
		'late': '迟到',
		'early': '早退',
		'working': '工作中',
		'absent': '缺勤',
		'missed': '漏打卡'
	}
	return statusMap[status] || '未知'
}

// 加载考勤记录
const loadAttendanceRecords = async () => {
	if (!isLoggedIn()) return

	recordsLoading.value = true

	try {
		// 获取当前日期所在周的起止时间
		const now = new Date()
		const day = now.getDay() || 7 // 将周日的0转换为7
		const startDate = new Date(now)
		startDate.setDate(now.getDate() - day + 1) // 周一
		startDate.setHours(0, 0, 0, 0)

		const endDate = new Date(now)
		endDate.setDate(now.getDate() + (7 - day)) // 周日
		endDate.setHours(23, 59, 59, 999)

		const params = {
			start_date: startDate.toISOString(),
			end_date: endDate.toISOString()
		}

		const res = await attendanceApi.getRecords(params)

		if (res.success && res.data) {
			// 将API返回的数据转换为组件需要的格式
			attendanceRecords.value = res.data.map((record: any) => {
				const recordDate = new Date(record.date)
				const month = String(recordDate.getMonth() + 1).padStart(2, '0')
				const day = String(recordDate.getDate()).padStart(2, '0')
				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

				return {
					date: `${month}-${day}`,
					weekday: weekdays[recordDate.getDay()],
					checkIn: record.check_in ? formatTime(new Date(record.check_in)) : '',
					checkOut: record.check_out ? formatTime(new Date(record.check_out)) : '',
					status: record.status
				}
			})
		}
	} catch (error) {
		console.error('获取考勤记录失败:', error)
	} finally {
		recordsLoading.value = false
	}
}

// 显示补卡申请表单
const showMissedPunchForm = () => {
	if (!isLoggedIn()) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}

	uni.navigateTo({
		url: '/pages/attendance/missed-punch'
	})
}

// 生命周期钩子
onLoad(() => {
	updateTime()
	// 每秒更新时间
	setInterval(() => {
		updateTime()
	}, 1000)
})

onShow(async () => {
	if (isLoggedIn()) {
		loadTodayAttendance()
		loadAttendanceRecords()

		// 重新加载项目列表
		await loadProjects()
		getLocation() // 重新获取位置
	}
})
</script>

<style scoped>
.attendance-container {
	padding: 0;
	background-color: #f5f6fa;
	min-height: 100vh;
}

/* 项目选择样式 */
.section {
	background: white;
	border-radius: 16rpx;
	padding: 32rpx;
	margin: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.project-section {
	margin-bottom: 24rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 24rpx;
	display: block;
}

.project-selector {
	background: #f8f9fa;
	border-radius: 8rpx;
	border: 1px solid #e9ecef;
}

.picker-content {
	padding: 24rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.picker-text {
	font-size: 30rpx;
	color: #333;
}

.picker-arrow {
	font-size: 24rpx;
	color: #999;
}

.map-container {
	position: relative;
	width: 100%;
	height: 450rpx;
	/* Increased height to provide more space for the map */
}

.attendance-map {
	width: 100%;
	height: 100%;
}

.map-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	background-color: rgba(255, 107, 107, 0.9);
	color: white;
	padding: 20rpx 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.map-overlay.in-range {
	background-color: rgba(76, 175, 80, 0.9);
}

.range-text {
	font-size: 30rpx;
	font-weight: bold;
}

.range-help {
	font-size: 24rpx;
}

.punch-container {
	display: flex;
	justify-content: center;
	margin-top: 80rpx;
	/* Changed from -50rpx to 20rpx to completely move button below map */
	margin-bottom: 40rpx;
	position: relative;
	z-index: 10;
}

.punch-circle {
	width: 300rpx;
	height: 300rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #FFC107, #FF9800);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	box-shadow: 0 8rpx 24rpx rgba(255, 152, 0, 0.3);
	transition: all 0.3s ease;
}

.punch-circle:active {
	transform: scale(0.95);
}

.punch-circle.disabled {
	opacity: 0.6;
	background: linear-gradient(135deg, #cccccc, #999999);
	box-shadow: 0 8rpx 24rpx rgba(153, 153, 153, 0.3);
}

.punch-content {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.punch-type {
	color: white;
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.punch-time {
	color: white;
	font-size: 48rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.punch-note {
	color: rgba(255, 255, 255, 0.8);
	font-size: 24rpx;
}

.work-time-info {
	text-align: center;
	margin-bottom: 40rpx;
}

.work-time-text {
	color: #666;
	font-size: 28rpx;
}

.location-info {
	padding: 16rpx;
}

.attendance-records {
	background: white;
	border-radius: 16rpx;
	padding: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	margin: 0 32rpx 40rpx;
}

.records-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 24rpx;
	display: block;
}

.record-item {
	display: flex;
	align-items: center;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.record-item:last-child {
	border-bottom: none;
}

.record-date {
	flex: 1;
}

.date {
	font-size: 32rpx;
	color: #333;
	display: block;
}

.weekday {
	font-size: 24rpx;
	color: #999;
}

.record-times {
	flex: 2;
	text-align: center;
}

.time-in,
.time-out {
	font-size: 28rpx;
	color: #666;
	margin: 0 16rpx;
}

.record-status {
	flex: 1;
	text-align: right;
	font-size: 28rpx;
}

.record-status.normal {
	color: #4caf50;
}

.record-status.late {
	color: #ff9800;
}

.record-status.working {
	color: #2196f3;
}

.record-status.absent {
	color: #f44336;
}

.record-status.missed {
	color: #9c27b0;
}

.missed-punch-section {
	padding: 0 32rpx 32rpx;
}

.missed-punch-button {
	width: 100%;
	background: #ffffff;
	color: #FF9800;
	border: 1rpx solid #FF9800;
	border-radius: 12rpx;
	padding: 24rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.empty-data,
.loading-data {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx 0;
}

.empty-text,
.loading-text {
	font-size: 28rpx;
	color: #999;
}
</style>